using System;
using System.Globalization;
using System.Linq;
using System.Reflection;

namespace UnitTesting.Fixturing
{
	class XthTypedArgument<T> : GenericTypedArgument<T>
	{
		readonly int _xthTyped;

		public int XthTyped
		{
			get { return _xthTyped; }
		}

		internal XthTypedArgument(int xthTyped, T value)
			: base(value)
		{
			if (xthTyped < 1)
			{
				throw new ArgumentException(
					string.Format(CultureInfo.InvariantCulture, "The Xth type number '{0}' should be great thatn zero.", xthTyped));
			}
			_xthTyped = xthTyped;
		}

		public override bool Equals(ParameterInfo parameterInfo)
		{
			var result = GetXthTypedParameter(parameterInfo);
			return result != null && result == parameterInfo;
		}

		ParameterInfo GetXthTypedParameter(ParameterInfo parameterInfo)
		{
			int matchCount = 0;
			var result = GetConstructor(parameterInfo).GetParameters().SkipWhile(x =>
			{
				if (base.Equals(x))
					matchCount++;
				return XthTyped != matchCount;
			}).FirstOrDefault();
			return result;
		}

		static ConstructorInfo GetConstructor(ParameterInfo parameterInfo)
		{
			return (ConstructorInfo) parameterInfo.Member;
		}

		public override string ToString()
		{
			return string.Format(CultureInfo.InvariantCulture, "XthTyped: {1}, {0}", base.ToString(), XthTyped);
		}
	}
}